<template>
  <div>
    <el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="0px"
             label-position="left"
             :style="{marginTop: '20px'}">
      <!-- 第一行: 下拉框 + 输入框 + 按钮 -->
      <el-row gutter="13" justify="center">
        <el-col :span="2">
          <!--          <el-form-item label-width="-1px" label="" prop="MainType">-->
          <!--            <el-select v-model="formData.MainType" placeholder="关键词" clearable :style="{width: '100%'}">-->
          <!--              <el-option v-for="(item, index) in MainTypeOptions" :key="index" :label="item.label"-->
          <!--                         :value="item.value" :disabled="item.disabled"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label-width="-1px" label="" prop="MainTypeLogic">
            <el-select
                v-model="formData.MainTypeLogic"
                placeholder="AND"
                :style="{width: '100%'}"
            >
              <el-option
                  v-for="(item, index) in LogicOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label-width="-1px" label="" prop="MainTypeValue">
            <el-input
                v-model="formData.MainTypeValue"
                placeholder="请输入"
                clearable
                class="input-with-select"
            >
              <template #prepend>  <!-- 使用 v-slot 语法 -->
                <el-select
                    v-model="formData.MainType"
                    placeholder="关键词"
                    style="width: 100px"
                >
                  <el-option
                      v-for="(item, index) in MainTypeOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="-2px" label="">
            <el-button @click="addRow">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 第二行: 下拉框 + 输入框 + 按钮 -->
      <el-row gutter="13" justify="center">
        <el-col :span="2">
          <!--          <el-form-item label-width="-1px" label="" prop="secondMainTypeValue">-->
          <!--            <el-select v-model="formData.secondMainType" placeholder="关键词" clearable :style="{width: '100%'}">-->
          <!--              <el-option v-for="(item, index) in SecondTypeOptions" :key="index" :label="item.label"-->
          <!--                         :value="item.value" :disabled="item.disabled"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label-width="-1px" label="" prop="secondMainTypeLogic">
            <el-select
                v-model="formData.secondMainTypeLogic"
                placeholder="AND"
                :style="{width: '100%'}"
            >
              <el-option
                  v-for="(item, index) in LogicOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label-width="-1px" label="" prop="secondMainTypeValue">
            <el-input
                v-model="formData.secondMainTypeValue"
                placeholder="请输入"
                clearable
                class="input-with-select"
            >
              <template #prepend>  <!-- 使用 v-slot 语法 -->
                <el-select
                    v-model="formData.secondMainType"
                    placeholder="关键词"
                    style="width: 100px"
                >
                  <el-option
                      v-for="(item, index) in SecondTypeOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="-2px" label="">
            <el-button @click="addRow">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
            <el-button @click="removeRow">
              <el-icon>
                <Minus/>
              </el-icon>
            </el-button>
          </el-form-item>

        </el-col>

      </el-row>

      <!-- 动态条件行 -->
      <el-row v-for="(row, index) in dynamicRows" :key="index" gutter="13" justify="center">
        <el-col :span="2">
          <!--          <el-form-item label-width="-1px" label="" :prop="`dynamicRows[${index}].field`">-->
          <!--            <el-select v-model="row.field" placeholder="关键词" clearable :style="{width: '100%'}">-->
          <!--              <el-option v-for="(item, index) in MainTypeOptions" :key="index" :label="item.label"-->
          <!--                         :value="item.value" :disabled="item.disabled"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label-width="-1px" label="" :prop="`dynamicRows[${index}].logic`">
            <el-select
                v-model="row.logic"
                placeholder="AND"
                :style="{width: '100%'}"
            >
              <el-option
                  v-for="(item, optIndex) in LogicOptions"
                  :key="optIndex"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label-width="-2px" label="" :prop="`dynamicRows[${index}].value`">

            <el-input
                v-model="row.value"
                placeholder="请输入"
                clearable
                class="input-with-select"
            >
              <template #prepend>
                <el-select
                    v-model="row.field"
                    placeholder="关键词"
                    style="width: 100px"
                    clearable
                >
                  <el-option
                      v-for="(item, optIndex) in MainTypeOptions"
                      :key="optIndex"
                      :label="item.label"
                      :value="item.value"

                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="-2px" label="">
            <el-button @click="addRow">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
            <el-button @click="removeDynamicRow(index)">
              <el-icon>
                <Minus/>
              </el-icon>
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 第二行: 多选框 -->
      <el-row justify="center">
        <el-form-item label="" prop="DocumentType">
          <el-checkbox-group v-model="formData.DocumentType" size="default">
            <el-checkbox v-for="(item, index) in DocumentTypeOptions" :key="index" :label="item.value"
                         :disabled="item.disabled">{{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>

      <!-- 提交按钮 -->
      <el-row gutter="20" justify="center">
        <el-form-item label-width="3px" label="">
          <el-button type="primary" icon="Search" size="default" @click="submitForm"> 搜索</el-button>

        </el-form-item>
        <el-form-item label-width="3px" label="">
          <el-button type="primary" icon="Refresh" size="default" @click="resetQuery"> 重置</el-button>

        </el-form-item>
      </el-row>


    </el-form>
    <el-table v-loading="loading" :data="SearchList">
      <el-table-column label="档号" align="center" prop="mysqlDanghao">
        <template #default="{row}">
            <span v-if="row.highlights && row.highlights.mysqlDanghao"
                  v-html="row.highlights.mysqlDanghao[0]"></span>
          <span v-else>{{ row.mysqlDanghao }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title">
        <template #default="{row}">
          <span v-if="row.highlights && row.highlights.title"
                v-html="row.highlights.title[0]"></span>
          <span v-else>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介/描述" align="center" prop="description">
        <template #default="{row}">
          <span v-if="row.highlights && row.highlights.description"
                v-html="row.highlights.description[0]"></span>
          <span v-else>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保密等级" align="center" prop="secretLevel"/>
      <!--      <el-table-column label="创建时间" align="center" prop="createTime" />-->
      <el-table-column label="文件类型" align="center" prop="fileType"/>
      <el-table-column label="文件路径" align="center" prop="filePath">
        <template #default="{row}">
          <span v-if="row.highlights && row.highlights.filePath"
                v-html="row.highlights.filePath[0]"></span>
          <span v-else>{{ row.filePath }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)" v-hasPermi="['manage:document:query']">查看
          </el-button>
          <!--移架操作-->
          <el-button link type="primary" @click="handleMove(scope.row)">移架操作</el-button>
        </template>
        <!--        点击查看嵌套文档内容的功能-->
        <!--        <template #default="{row}">-->
        <!--          <el-button @click="handleDetail(row)">查看档案</el-button>-->
        <!--          <el-button-->
        <!--              v-if="row.documents && row.documents.length > 0"-->
        <!--              @click="showDocumentDetails(row.documents[0], row)"-->
        <!--          >-->
        <!--            查看文档-->
        <!--          </el-button>-->
        <!--        </template>-->
      </el-table-column>

    </el-table>
    <!-- 添加嵌套文档的高亮显示对话框 -->
    <el-dialog v-model="documentDialogVisible" title="文档内容" width="70%">
      <div v-if="currentDocument">
        <h3 v-if="currentDocumentHighlights && currentDocumentHighlights.docTitle"
            v-html="currentDocumentHighlights.docTitle[0]"></h3>
        <h3 v-else>{{ currentDocument.docTitle }}</h3>

        <div v-if="currentDocumentHighlights && currentDocumentHighlights.docContent"
             v-html="currentDocumentHighlights.docContent[0]"></div>
        <div v-else>{{ currentDocument.docContent }}</div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {ElMessage, ElMessageBox} from "element-plus";
import {ElasticsearchArchiveList} from "@/api/manage/ElasticsearchArchive.js";
import {Plus, Minus} from '@element-plus/icons-vue'; // 引入图标


import {ref, reactive, toRefs, getCurrentInstance} from 'vue';
import {useRouter} from 'vue-router';
import axios from 'axios'; // 确保引入 axios
import {getArchiveIdByMysqlDanghao, getArchiveLocationByMysqlDanghao} from "@/api/manage/archive.js";
import {getInfo} from "@/api/login.js";
import {unlockColumn,leftMoveColumn, rightMoveColumn,getColumnStatus} from "@/api/system/move.js"; // 引入新函数
const {proxy} = getCurrentInstance();
const router = useRouter();


const loading = ref(false);
const SearchList = ref([]);
const total = ref(0);
// const dynamicRows = ref([]); // 动态条件行
const dynamicRows = ref([{field: 'title', value: '', logic: 'AND'}]);


// 计算当前文档的高亮内容
const currentDocumentHighlights = computed(() => {
  if (!currentDocument.value || !currentDocument.value._parent) return null;
  return currentDocument.value._parent.highlights;
});

const formRef = ref()
const data = reactive({
  formData: {
    MainType: 'title',
    MainTypeValue: undefined,
    MainTypeLogic: 'AND',
    secondMainType: 'title',
    secondMainTypeValue: undefined,
    secondMainTypeLogic: 'AND',
    DocumentType: [],
  },
  rules: {
    MainType: [{
      required: true,
      message: '关键词',
      trigger: 'change'
    }],

    secondMainType: [{
      required: false,
      message: '关键词',
      trigger: 'change'
    }],
    MainTypeValue: [{
      required: true,
      message: '请输入',
      trigger: 'blur'
    }],
    secondMainTypeValue: [{
      required: false,
      message: '关键字',
      trigger: 'change'
    }],
  }
})
const {
  formData,
  rules
} = toRefs(data)
const MainTypeOptions = ref([{
  "label": "标题",
  "value": "title"
}, {
  "label": "简介",
  "value": "description"
}, {
  "label": "档号",
  "value": "mysqlDanghao"
}, {
  "label": "路径",
  "value": "filePath"
}, {label: "文档标题", value: "documents.docTitle"},
  {label: "文档内容", value: "documents.docContent"}
])
const SecondTypeOptions = ref([{
  "label": "标题",
  "value": "title"
}, {
  "label": "简介",
  "value": "description"
}, {
  "label": "档号",
  "value": "mysqlDanghao"
}, {
  "label": "路径",
  "value": "filePath"
}, {label: "文档标题", value: "documents.docTitle"},
  {label: "文档内容", value: "documents.docContent"}
])
const DocumentTypeOptions = ref([{
  "label": "电子档案",
  "value": 1
}, {
  "label": "实体档案",
  "value": 2
}])

const LogicOptions = ref([
  {label: 'AND', value: 'AND', disabled: false},
  {label: 'OR', value: 'OR', disabled: false},
  {label: 'NOT', value: 'NOT', disabled: false}
]);

/**
 * @name: 表单提交
 * @description: 表单提交方法
 * @return {*}
 */

//handleMove移架操作
async function handleMove(row) {
  console.log('row:', row)
  const dangAnHao = row.mysqlDanghao;
  // 根据档案号查询档案位置
  await getArchiveLocationByMysqlDanghao(dangAnHao).then(response => {
    console.log('response:', response);
    let location = typeof response === 'string' ? response : response.data;
    console.log('location:', location);
    handleMoveProcess({shitiLocation:location},  dangAnHao)
  });
}


// 移动架子的操作handleMove   likang
async function handleMoveProcess(row,dangAnHao) {

  // console.log('列数据',row.shitiLocation)
  const quHao = row.shitiLocation.split('-')[0]
  // .substring(0, 1);
  const lieHao = row.shitiLocation.split('-')[1]
  // .substring(0, 1);
  const AorB = row.shitiLocation.split('-')[2]
  // .substring(0, 1);


  // 判断row.shitiLocation安装位置格式是否正确
  if (row.shitiLocation.split('-').length !== 3) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;您的格式为:' + row.shitiLocation,
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }
  let quHaoList = ['1', '2', '3', '4']
  let lieHaoList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  // 判断quHao是否在quHaoList中
  if (!quHaoList.includes(quHao)) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;' +
        '实际代表1区2列左边。' +
        '但是您的格式为:' + row.shitiLocation + ';请先修改。ps:区号只有1-4,列号只有1-18',
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }
  // 判断lieHao是否在lieHaoList中
  if (!lieHaoList.includes(lieHao)) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;' +
        '实际代表1区2列左边。' +
        '但是您的格式为:' + row.shitiLocation + ';请先修改。ps:区号只有1-4,列号只有1-18',
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }


  // 是否开架
  await proxy.$modal.confirm('是否确认打开[解锁]编号为"' + dangAnHao + '"的档案所在列？具体为' + row.shitiLocation)
      .then(async () => {
        const loadingInstance = proxy.$loading({
          lock: true,
          text: "正在发送解锁指令...",
          spinner: "el-icon-loading",
        });
        // 根据 quHao查找ip和端口
        await getInfo(quHao).then(async (response) => {
          const ip = response.data.gdlIp;
          const port = response.data.gdlPort;
          // 先进行解锁操作
          await unlockColumn(ip, port).  //原
              then(async (response) => {
                // console.log('解锁返回',response)
                if (response.data.data == "1") { //原
                  loadingInstance.close();
                  ElMessage({
                    message: '列解锁成功...',
                    type: 'success',
                    duration: 1500
                  })
                  const loadingInstance2 = proxy.$loading({
                    lock: true,
                    text: "正在获取柜子状态...",
                    spinner: "el-icon-loading",
                  });
                  // 进门左手的档案柜
                  if (quHao == 1 || quHao == 2 || quHao == '1' || quHao == '2') {
                    // 看左侧
                    if (AorB == 'A') {
                      // 获取列状态
                      await getColumnStatus(ip, port)
                          .then(async (response) => {
                            loadingInstance2.close()
                            const loadingInstance3 = proxy.$loading({
                              lock: true,
                              text: "正在发送移动指令...",
                              spinner: "el-icon-loading",
                            });
                            // 列到位状态字符串：0231，说明该组密集架共有4列，
                            // 第一列状态是0，表示两边均未到位；
                            // 第二列状态是2，表示只有右边到位；
                            // 第三列状态是3，表示两边均到位；
                            // 第四列状态是1表示只有左边到位。
                            const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                            // 判断ColumnStatus中第lieHao的数值
                            if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 1 || ColumnStatus[lieHao - 1] == 3) {
                              // 列均未到位 || 列右边未到位 || 都到位
                              await rightMoveColumn(ip, port, lieHao)
                                  .then(response => {
                                    console.log('右移1成功',response)
                                    loadingInstance3.close()
                                    if (response.data.data == "1") {
                                      console.log('右移1成功2',response)
                                      ElMessage({
                                        message: '正在移动柜子，请耐心等待，或观看监控状态',
                                        type: 'success',
                                        duration: 2500
                                      })
                                      // loadingV.value = true;
                                    }
                                  })
                                  .catch(error => {
                                    loadingInstance3.close()
                                    console.log('右移1失败',response)
                                    // ElMessage({
                                    //   message: '右移操作失败',
                                    //   type: 'error'
                                    // })
                                  });
                            } else if (ColumnStatus[lieHao - 1] == 2) {
                              //  只有右边到位，说明左边未到位，本来就是查看左边，所以不用管
                              console.log('只有右边到位，说明左边未到位，本来就是查看左边，所以不用管')
                            }
                          })
                          .catch(error => {
                            loadingInstance2.close()
                            console.log('获取列状态失败')
                          });
                    } else if (AorB == 'B') {
                      await getColumnStatus(ip, port).then(async response => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        // 列到位状态字符串：0231，说明该组密集架共有4列，
                        // 第一列状态是0，表示两边均未到位；
                        // 第二列状态是2，表示只有右边到位；
                        // 第三列状态是3，表示两边均到位；
                        // 第四列状态是1表示只有左边到位。
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        // 判断ColumnStatus中第lieHao的数值
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 2) {
                          // 列均未到位 || 列左边不到位
                          await leftMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('左移1成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                  // loadingV.value = true;
                                }
                                console.log(response);
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移1失败',response)
                                // ElMessage({
                                //   message: '左移操作失败',
                                //   type: 'error'
                                // })
                              })
                        } else if (ColumnStatus[lieHao - 1] == 3) {
                          // 3两侧均到位      则2+1号柜子右移
                          rightMoveColumn(ip, port, lieHao + 1)
                              .then(response => {
                                console.log('右移2成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                  // loadingV.value = true;
                                }
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('右移2失败',response)
                                // ElMessage({
                                //   message: '右移操作失败',
                                //   type: 'error'
                                // })
                              });
                        } else if (ColumnStatus[lieHao - 1] == 1) {
                          // 1左侧到位 就是右侧不到位
                          // 不用管
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                        console.log('获取列状态失败')
                      });
                    }
                  }
                  // 进门右手的档案柜
                  else if (quHao == 3 || quHao == 4 || quHao == '3' || quHao == '4') {
                    if (AorB == 'A') {
                      // 获取列状态
                      await getColumnStatus(ip, port).then(async (response) => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        // 列到位状态字符串：0231，说明该组密集架共有4列，
                        // 第一列状态是0，表示两边均未到位；
                        // 第二列状态是2，表示只有右边到位；
                        // 第三列状态是3，表示两边均到位；
                        // 第四列状态是1表示只有左边到位。
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        // 判断ColumnStatus中第lieHao的数值
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 1) {
                          // 列均未到位 || 列右边未到位
                          await rightMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('右移3成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  loadingInstance3.close()
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                }
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('右移3失败',response)
                              });
                        } else if (ColumnStatus[lieHao - 1] == 3) {
                          await leftMoveColumn(ip, port, lieHao + 1)
                              .then(response => {
                                console.log('左移2成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                }
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移2失败',response)
                                // ElMessage({
                                //   message: '左移操作失败',
                                //   type: 'error'
                                // })
                              });
                        } else if (ColumnStatus[lieHao - 1] == 2) {
                          // 不用管
                          console.log('')
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                        console.log('获取列状态失败')
                      });
                    }
                    else if (AorB == 'B') {
                      await getColumnStatus(ip, port).then(async (response) => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 2 || ColumnStatus[lieHao - 1] == 3) {
                          await leftMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('左移3成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                }
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移3失败',response)

                                // ElMessage({
                                //   message: '左移操作失败',
                                //   type: 'error'
                                // })
                              });
                        } else if (ColumnStatus[lieHao - 1] == 1) {
                          console.log('不用管')
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                      });
                    }
                  }
                }
              })
              .catch(error => {
                loadingInstance.close();
                ElMessage({
                  message: '解锁失败',
                  type: 'error',
                  duration: 5000
                })
              })
        });
      })
      .catch(() => {
      });
}

/** 查看详情按钮操作 */
// function handleDetail(row) {
//   const danghao = row.danghao.id;
//   // 调用后端接口根据 danghao 获取档案的 id
//   getArchiveIdByDanghao(danghao).then(response => {
//     const archiveId = response.data;
//     // 跳转到详情页
//     proxy.$router.push({ path: '/manage/archive/arc-detail/', query: { id: archiveId } });
//   });
// }
function handleDetail(row) {
  const mysqlDanghao = row.mysqlDanghao;
  console.log('mysqlDanghao:', mysqlDanghao);
  // 调用后端接口根据 mysqlDanghao 获取 archiveId
  getArchiveIdByMysqlDanghao(mysqlDanghao).then(response => {
    console.log('response:', response);
    // const archiveId = response.data;
    // 根据archiveId返回类型进行不同的处理
    let archiveId = typeof response === 'number' ? response : response.data;
    console.log('archiveId:', archiveId);

    // 跳转参数
    proxy.$router.push({
      path: '/manage/archive/arc-detail/',
      query: {
        id: response.data || response,
        fromSearch: true,
        searchText: formData.value.MainTypeValue, // 传递搜索词
        searchField: formData.value.MainType,     // 传递搜索字段
        globalSort: true
      }
    });
  });

}

// 查看文档内容（点击查看嵌套文档内容的方法）
function showDocumentDetails(document, parent) {
  // 将父级的高亮信息附加到文档对象上
  document._parent = parent;
  currentDocument.value = document;
  documentDialogVisible.value = true;
}


// 添加条件行
const addRow = () => {
  dynamicRows.value.push({field: '', value: '', logic: 'AND'});
};

// 静态删除条件行
const removeRow = () => {
  if (dynamicRows.value.length > 0) {
    dynamicRows.value.pop();
  }
};
// 动态行删除方法
const removeDynamicRow = (index) => {
  if (dynamicRows.value.length > 0) {
    dynamicRows.value.splice(index, 1)
  }
}

/** 重置按钮操作 */
function resetQuery() {
  // 重置表单验证状态
  formRef.value.resetFields();

  // 重置静态表单数据
  formData.value = {
    MainType: 'title',
    MainTypeValue: undefined,
    MainTypeLogic: 'AND',
    secondMainType: 'title',
    secondMainTypeValue: undefined,
    secondMainTypeLogic: 'AND',
    DocumentType: [],
  };

  // 重置动态行内容
  dynamicRows.value = dynamicRows.value.map(() => ({
    field: 'title',
    value: '',
    logic: 'AND'
  }));
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 合并静态条件和动态条件
      const searchParams = {
        MainType: formData.value.MainType,
        MainTypeValue: formData.value.MainTypeValue,
        MainTypeLogic: formData.value.MainTypeLogic, // 添加静态条件的逻辑
        secondMainType: formData.value.secondMainType,
        secondMainTypeValue: formData.value.secondMainTypeValue,
        secondMainTypeLogic: formData.value.secondMainTypeLogic, // 添加静态条件的逻辑
        DocumentType: formData.value.DocumentType.join(','), // 将数组转换为字符串
      };
      // 添加动态条件
      dynamicRows.value.forEach((row, index) => {
        searchParams[`dynamicField${index}`] = row.field; // 动态字段名
        searchParams[`dynamicValue${index}`] = row.value; // 动态字段值
        searchParams[`dynamicLogic${index}`] = row.logic; // 动态字段值
      });
      // 动态条件改为数组格式（推荐）
      // dynamicConditions: dynamicRows.value.map(row => ({
      //   logic: row.logic,  // 动态条件的逻辑
      //   field: row.field,  // 动态条件的字段
      //   value: row.value   // 动态条件的值
      // }));
      console.log('提交的参数：', searchParams); // 打印参数
      // 调用搜索接口
      getList(searchParams);
    } else {
      console.log('表单验证失败');
    }
  });
};

function getList(searchParams) {
  loading.value = true;
  ElasticsearchArchiveList(searchParams).then(response => {
    // 处理返回数据，确保高亮信息正确
    SearchList.value = response.rows.map(item => {
      // 处理嵌套文档的高亮
      if (item.documents && item.highlights) {
        item.documents.forEach(doc => {
          // 将父级的高亮信息附加到文档对象上
          doc._parent = item;
        });
      }
      return item;
    });
    total.value = response.total;

    // 2. 新增：显示权限提示
    if (response.msg) {
      ElMessage({
        type: 'warning',      // 使用警告类型（黄色）
        message: response.msg,
        duration: 5000,       // 显示5秒
        showClose: true       // 显示关闭按钮
      });
    }
    loading.value = false;
    // proxy.$modal.message({
    //   message: '搜索成功',
    // });

  }).catch(error => {
    loading.value = false;
    ElMessage.error('搜索失败: ' + error.message);
  });
};


</script>
<style>


/* 高亮样式 */
.highlight {
  background-color: transparent; /* 透明背景 */
  color: red; /* 红色字体 */
  font-weight: bold;
  padding: 0 2px;
  border-radius: 2px;
  text-decoration: none;

}

/* 调整组合输入框样式 */
.input-with-select {
  width: 100%;
}

/* 调整选择框宽度 */
:deep(.input-with-select .el-select) {
  width: 120px;
}

/* 保持输入框和选择框高度一致 */
:deep(.input-with-select .el-input-group__prepend) {
  background-color: #fff;
  padding: 0 12px;
}
</style>
